const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
const TopCategory = require('../models/TopCategory');
const SubCategory = require('../models/SubCategory');

const errorRes = (res, message, code = 400) => res.status(code).json({ code, message });

// 获取所有商品
router.get('/list', async (req, res) => {
  try {
    const { topCate, page, userId } = req.query;
    const query = {};
    if (topCate != 1) query.topCategory = topCate;
    if (userId) query.userId = userId;

    if (userId) {
      const User = require('../models/User');
      const user = await User.findById(userId);
      if (!user || user.status !== '正常') {
        return errorRes(res, '当前账号状态异常，无法进行商品管理操作，请联系管理员。', 403);
      }
    }

    const products = await Product.find(query)
      .populate('topCategoryInfo', 'name')
      .populate('subCategoryInfo', 'name')
      .limit(10)
      .skip((page - 1) * 10);

    res.json({ code: 200, products });
  } catch (e) {
    errorRes(res, '获取商品失败', 500);
  }
});

// 获取所有大分类
router.get('/catetopgory', async (req, res) => {
  const categories = await TopCategory.find();
  res.json({ code: 200, categories });
});

// 获取所有分类及其子表
router.get('/category', async (req, res) => {
  try {
    const categories = await TopCategory.aggregate([
      {
        $lookup: {
          from: 'subcategories',
          localField: '_id',
          foreignField: 'parent',
          as: 'subCategories'
        }
      }
    ]);
    res.json({ code: 200, categories });
  } catch (e) {
    errorRes(res, '服务器错误', 500);
  }
});

// 获取所有子分类
router.get('/catesubgory', async (req, res) => {
  const categories = await SubCategory.find();
  res.json({ code: 200, categories });
});

// 获取商品分类分布
router.get('/category-distribution', async (req, res) => {
  try {
    const topCategories = await TopCategory.find();
    const categoryDistribution = await Promise.all(
      topCategories.map(async (category) => {
        const count = await Product.countDocuments({ topCategory: category._id });
        return { name: category.name, count };
      })
    );
    const totalProducts = categoryDistribution.reduce((sum, category) => sum + category.count, 0);
    const result = categoryDistribution
      .map(category => ({
        name: category.name,
        count: category.count,
        percentage: totalProducts > 0 ? Math.round((category.count / totalProducts) * 100) : 0
      }))
      .filter(category => category.count > 0)
      .sort((a, b) => b.count - a.count);
    res.json({ code: 200, data: result, message: '获取商品分类分布成功' });
  } catch (e) {
    errorRes(res, '获取商品分类分布失败', 500);
  }
});

// 获取商品类别销量数据
router.get('/category-sales', async (req, res) => {
  try {
    const topCategories = await TopCategory.find();
    const categorySalesData = await Promise.all(
      topCategories.map(async (category) => {
        const products = await Product.find({ topCategory: category._id });
        const salesVolume = products.reduce((total, product) => total + (product.sales || 0), 0);
        return { name: category.name, salesVolume, productCount: products.length };
      })
    );
    const result = categorySalesData
      .filter(category => category.salesVolume > 0)
      .sort((a, b) => b.salesVolume - a.salesVolume);
    res.json({ code: 200, data: result, message: '获取商品类别销量数据成功' });
  } catch (e) {
    errorRes(res, '获取商品类别销量数据失败', 500);
  }
});

// 获取所有商品总件数
router.get('/total-count', async (req, res) => {
  const data = await Product.countDocuments();
  res.json({ code: 200, data, message: '获取商品总数成功' });
});

// 获取id对应商品的数据
router.get('/cateListid', async (req, res) => {
  const data = await Product.find({ _id: req.query.id });
  res.json({ code: 200, data });
});

// 获取筛选后的商品数据
router.get('/listfind', async (req, res) => {
  const { subCategory, page = 1, name } = req.query;
  const query = {};
  if (subCategory) query.subCategory = subCategory;
  if (name) query.name = { $regex: name, $options: 'i' };
  const data = await Product.find(query).limit(10).skip((page - 1) * 10);
  res.json({ code: 200, data });
});

// 获取平台总销售量
router.get('/total-sales-volume', async (req, res) => {
  try {
    const Role = require('../models/Role');
    const adminRole = await Role.findOne({ name: 'admin' });
    if (!adminRole) return errorRes(res, '获取角色信息失败', 500);
    // 实际应从订单表获取，这里为模拟数据
    const data = 12680;
    res.json({ code: 200, data, message: '获取平台总销售量成功' });
  } catch (e) {
    errorRes(res, '获取平台总销售量失败', 500);
  }
});

// 获取平台总销售额
router.get('/total-sales', async (req, res) => {
  try {
    const Role = require('../models/Role');
    const User = require('../models/User');
    const adminRole = await Role.findOne({ name: 'admin' });
    if (!adminRole) return errorRes(res, '获取角色信息失败', 500);
    const merchants = await User.find({ roles: { $nin: [adminRole._id] }, isVerified: true }).select('_id');
    const merchantIds = merchants.map(merchant => merchant._id);
    const products = await Product.find({ userId: { $in: merchantIds } });
    let totalSales = 0;
    products.forEach(product => {
      const productSales = product.price * (product.sales || 0);
      totalSales += productSales;
    });
    const formattedSales = totalSales.toFixed(2);
    res.json({ code: 200, data: formattedSales, message: '获取平台总销售额成功' });
  } catch (e) {
    errorRes(res, '获取平台总销售额失败', 500);
  }
});

// 添加商品
router.post('/add', async (req, res) => {
  try {
    const { name, description, price, image, images, stock, topCategory, subCategory, isUp, Tabs,userId } = req.body;
    if (!name || !description || !price || !image || !topCategory || !subCategory) {
      return errorRes(res, '请填写完整的商品信息');
    }
    const topCategoryDoc = await TopCategory.findOne({ name: topCategory });
    if (!topCategoryDoc) return errorRes(res, '大分类不存在');
    const newProduct = new Product({
      name,
      description,
      price,
      image,
      images: images || [],
      stock: stock || 100,
      topCategory: topCategoryDoc._id,
      subCategory,
      isUp: isUp || false,
      Tabs: Tabs || [],
      userId: userId
    })
  
    await newProduct.save()

    res.json({
      code: 200,
      message: '添加商品成功',
      data: newProduct
    })
  } catch (error) {
    console.error('添加商品失败:', error)
    res.status(500).json({
      code: 500,
      message: '添加商品失败',
      error: error.message
    })
  }
});

// 删除商品
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params
    const { userId } = req.body

    // 验证商品ID
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: '商品ID不能为空'
      })
    }

    // 验证用户ID
    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: '用户信息缺失'
      })
    }

    // 验证用户状态
    const User = require('../models/User')
    const user = await User.findById(userId)
    if (!user || user.status !== '正常') {
      return res.status(403).json({
        code: 403,
        message: '当前账号状态异常，无法进行商品管理操作，请联系管理员。'
      })
    }

    // 查找并删除商品
    const deletedProduct = await Product.findByIdAndDelete(id)
    
    if (!deletedProduct) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在'
      })
    }

    res.json({
      code: 200,
      message: '删除商品成功',
      data: deletedProduct
    })
  } catch (error) {
    console.error('删除商品失败:', error)
    res.status(500).json({
      code: 500,
      message: '删除商品失败',
      error: error.message
    })
  }
});

// 修改商品
router.post('/update/:id', async (req, res) => {
  try {
    const { id } = req.params
    const updateData = req.body
    const { userId } = updateData

    if (!id) {
      return res.status(400).json({ code: 400, message: '商品ID不能为空' })
    }

    // 验证用户ID
    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: '用户信息缺失'
      })
    }

    // 验证用户状态
    const User = require('../models/User')
    const user = await User.findById(userId)
    if (!user || user.status !== '正常') {
      return res.status(403).json({
        code: 403,
        message: '当前账号状态异常，无法进行商品管理操作，请联系管理员。'
      })
    }

    // 如果有 topCategory（大分类），需转为 ObjectId
    if (updateData.topCategory) {
      // 如果已经是ObjectId（24位字符串），直接用
      if (typeof updateData.topCategory === 'string' && updateData.topCategory.length === 24) {
        // do nothing
      } else {
        // 兼容老数据，查找name
        const topCategoryDoc = await TopCategory.findOne({ name: updateData.topCategory });
        if (topCategoryDoc) {
          updateData.topCategory = topCategoryDoc._id;
        } else {
          return errorRes(res, '大分类不存在');
        }
      }
    }
    const updated = await Product.findByIdAndUpdate(id, updateData, { new: true });
    if (!updated) return errorRes(res, '商品不存在', 404);
    res.json({ code: 200, message: '修改商品成功', data: updated });
  } catch (e) {
    errorRes(res, '修改商品失败', 500);
  }
});

module.exports = router; 